from rest_framework.exceptions import ValidationError

from apps.booking.models import Appointment, AppointmentClientServices
from apps.booking.telehealth import create_zoom_meeting, create_meeting
from apps.tenant.models import ProviderServices


def create_appointment(request, validated_data):
    start_date = validated_data.get('start_date', None)

    services = None
    if 'appointment_services' in validated_data:
        services = validated_data.pop('appointment_services')

    if start_date is None:
        validated_data['start_date'] = validated_data.get('booking').start_date

    telehealth = validated_data.get('telehealth', False)
    if telehealth is True:
        zoom = validated_data.get('zoom', False)
        google = validated_data.get('google', False)
        if zoom:
            validated_data['telehealth_zoom_id'] = create_zoom_meeting(validated_data.get('provider'), start_date,
                                                                       validated_data.get('start_time'),
                                                                       validated_data.get('end_time'))
        if google:
            validated_data['telehealth_google_id'] = create_meeting(validated_data.get('provider'), start_date,
                                                                    validated_data.get('start_time'),
                                                                    validated_data.get('end_time'))

    clients = validated_data.pop('clients')
    app = Appointment.objects.create(**validated_data)
    app.clients.set(clients)
    app.save()

    if services:
        save_client_services(app, services)
    return app


def save_client_services(app, clients):
    services = []
    for client in clients:
        if 'services' in client:

            client_id = client['id']
            for service_data in client['services']:
                provider_service = ProviderServices.objects.filter(id=service_data['service']).first()
                service = AppointmentClientServices(
                    appointment=app,
                    client_id=client_id,
                    service=provider_service,  # Assuming 'service' is the ID of ProviderServices
                    fees=service_data.get('fees', 0)  # Assuming 'fees' is optional and default to 0 if not provided
                )
                services.append(service)
        else:
            raise ValidationError({'msg': 'At least one service must be selected of the client'})
    if len(services) > 0:
        AppointmentClientServices.objects.bulk_create(services)
